using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
#if false
    [DisallowMultipleComponent]
    public class PrefabReferenceHolder : MonoBehaviour
    {
        public int instanceId;
        private GameObject prefab;
        private bool isAutoDestroy = false;
        private bool isRelease;
        private void Awake()
        {
            isAutoDestroy = false;
            instanceId = gameObject.GetInstanceID();
        }

        public void SetPrefab(GameObject prefab)
        {
            if (this.prefab == prefab) return;
            if (this.prefab != null) //释放旧引用资源计数
            {
                Release();
            }

            this.prefab = prefab;
            //此脚本也引用了一份prefab。则计数要+1
            Retain();
        }
        private void Retain()
        {
            if (this.prefab != null && !this.isRelease)
            {
                this.isRelease = PrefabPool.Instance.Retain(prefab);
            }
        }

        private void Release()
        {
            if (this.isRelease && this.prefab != null)
            {
                this.isRelease = false;
                PrefabPool.Instance.Free(this.prefab, false);
                this.prefab = null;
            }
        }

        private void OnDestroy()
        {
            if (isAutoDestroy) return; //避免缓存池再次销毁
            isAutoDestroy = true;
            if (GameObjectPool.Instance != null) GameObjectPool.Instance.Free(this.instanceId);
            Release();
            //GameObjectPool.Instance.Free(gameObject, true);
        }
    }
#endif
}
